const fs = require("fs");
const path = require("path");
const axios = require("axios");
const FormData = require("form-data");

// 图片扩展名数组
const imageExtensions = [
  ".jpg",
  ".jpeg",
  ".png",
  ".gif",
  ".bmp",
  ".svg",
  ".webp",
];

// 上传图片到数据库的接口URL
const uploadUrl = "http://localhost:8080/upload";

// 判断文件是否为图片文件
function isImageFile(file) {
  return imageExtensions.some((ext) => file.toLowerCase().endsWith(ext));
}

// 上传图片到数据库
async function uploadImage(filePath) {
  console.log(`Uploading ${filePath} to database...`);

  const formData = new FormData();
  formData.append("file", fs.createReadStream(filePath));

  try {
    const response = await axios.post(uploadUrl, formData, {
      headers: {
        ...formData.getHeaders(),
      },
    });

    console.log(`Uploaded ${filePath} to database: ${response.data}`);
  } catch (err) {
    console.error(`Error uploading ${filePath} to database: ${err}`);
  }
}

// 顺序上传图片
async function sequentialUploads(dirPath) {
  let files;
  try {
    files = await fs.promises.readdir(dirPath);
  } catch (err) {
    console.error(`Error reading directory ${dirPath}: ${err}`);
    return;
  }

  for (let file of files) {
    const filePath = path.join(dirPath, file);
    console.log(`Processing file: ${filePath}`);

    let stats;
    try {
      // 检查路径是否存在
      if (!fs.existsSync(filePath)) {
        console.error(`File path does not exist: ${filePath}`);
        continue;
      }

      stats = await fs.promises.stat(filePath);
    } catch (err) {
      console.error(`Error getting stats for file ${filePath}: ${err}`);
      continue; // 跳过出错的文件
    }

    if (stats.isDirectory()) {
      await sequentialUploads(filePath); // 递归处理子目录
    } else if (isImageFile(file)) {
      await uploadImage(filePath); // 如果是图片文件，则上传到数据库
    }
  }
}

// 主函数，开始执行
async function main() {
  const dirPath = "D:/ChineseBQB"; // 替换为你要读取的目录路径
  try {
    console.log(`Starting upload process for directory: ${dirPath}`);
    await sequentialUploads(dirPath);
  } catch (err) {
    console.error(`Error in main function: ${err}`);
  }
}

main();
